//
//  UserInfoViewModel.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/1.
//

import UIKit

class UserInfoViewModel {
    var nickName:String?
    var avatar_url:String?
    let uploadDoneSubject = PublishSubject<Void>()
    let okSubject = PublishSubject<Void>()
    
    func getData(){
        nickName = Appearance.shared.accoutModel?.nickname ?? ""
        avatar_url = Appearance.shared.accoutModel?.icon ?? ""
    }
    
    //更新用户信息
    func uploadUserInfo() {
        guard let nickname = self.nickName, nickname.count > 0 else {
            NDProgressHUD.showError(title: "", subtitle: "请检查昵称")
            return }
        // 提交用户信息修改
        NDProgressHUD.showLoading()
        RequestService.instance.editUserInfo(icon: self.avatar_url ?? "", nickName: nickname, completeClosure: {
            NDProgressHUD.showSuccess(title: "", subtitle: "更新成功")
            self.updateInfo()
            self.okSubject.onNext(())
        }, failureClosure: { err in
            NDProgressHUD.showError(title: "", subtitle: "更新出错")
        })
    }
    
    
    func uploadAvatar(_ image: UIImage?){
        guard let image = image else { return }
        let file = UploadFile(data: image.compressedData(quality: 0.5))
        NDProgressHUD.showLoading()
        RequestService.instance.UploadFile(file: file, completionHandler: { result in
            NDProgressHUD.hide()
            let result = result.replacingOccurrences(of: "http://", with: "https://")
            self.avatar_url = result
            Appearance.shared.accoutModel?.icon = result
            self.uploadDoneSubject.onNext(())
        }, failureHandler: { err in
            NDProgressHUD.showError(title: "", subtitle: "更新出错")
        })
    }
    
    func updateInfo(){
        Appearance.shared.accoutModel?.nickname = nickName ?? ""
        Appearance.shared.accoutModel?.icon = avatar_url ?? ""
        if let model = Appearance.shared.accoutModel {
            SqlManager.shared.update(on: AccountModel.Properties.all, with: model, where: AccountModel.Properties.userId == model.userId ?? 0)
        }
    }
}
